using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;

namespace Lzfy_Refund_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class PermissionController : ControllerBase
    {
        private readonly IPermissionService _permissionService;
        private readonly ILogger<PermissionController> _logger;

        public PermissionController(IPermissionService permissionService, ILogger<PermissionController> logger)
        {
            _permissionService = permissionService;
            _logger = logger;
        }

        /// <summary>
        /// 获取菜单树
        /// </summary>
        [HttpPost("menu-tree")]
        public async Task<IActionResult> GetMenuTree([FromBody] MenuTreeRequest request)
        {
            try
            {
                var menus = await _permissionService.GetMenuTreeAsync(request);
                return Ok(new { success = true, data = menus });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取菜单树失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取所有菜单
        /// </summary>
        [HttpGet("menus")]
        public async Task<IActionResult> GetAllMenus()
        {
            try
            {
                var menus = await _permissionService.GetAllMenusAsync();
                return Ok(new { success = true, data = menus });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有菜单失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取菜单详情
        /// </summary>
        [HttpGet("menus/{id}")]
        public async Task<IActionResult> GetMenuById(int id)
        {
            try
            {
                var menu = await _permissionService.GetMenuByIdAsync(id);
                if (menu == null)
                {
                    return NotFound(new { success = false, message = "菜单不存在" });
                }
                return Ok(new { success = true, data = menu });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取菜单详情失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 创建菜单
        /// </summary>
        [HttpPost("menus")]
        public async Task<IActionResult> CreateMenu([FromBody] MenuDto menuDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { success = false, message = "参数验证失败", errors = ModelState });
                }

                var menuId = await _permissionService.CreateMenuAsync(menuDto);
                return Ok(new { success = true, data = new { id = menuId }, message = "菜单创建成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建菜单失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新菜单
        /// </summary>
        [HttpPut("menus/{id}")]
        public async Task<IActionResult> UpdateMenu(int id, [FromBody] MenuDto menuDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { success = false, message = "参数验证失败", errors = ModelState });
                }

                var result = await _permissionService.UpdateMenuAsync(id, menuDto);
                if (result)
                {
                    return Ok(new { success = true, message = "菜单更新成功" });
                }
                return BadRequest(new { success = false, message = "菜单更新失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新菜单失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        [HttpDelete("menus/{id}")]
        public async Task<IActionResult> DeleteMenu(int id)
        {
            try
            {
                var result = await _permissionService.DeleteMenuAsync(id);
                if (result)
                {
                    return Ok(new { success = true, message = "菜单删除成功" });
                }
                return BadRequest(new { success = false, message = "菜单删除失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除菜单失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 切换菜单状态
        /// </summary>
        [HttpPost("menus/{id}/toggle-status")]
        public async Task<IActionResult> ToggleMenuStatus(int id, [FromBody] ToggleStatusRequest request)
        {
            try
            {
                var result = await _permissionService.ToggleMenuStatusAsync(id, request.IsActive);
                if (result)
                {
                    return Ok(new { success = true, message = "菜单状态更新成功" });
                }
                return BadRequest(new { success = false, message = "菜单状态更新失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "切换菜单状态失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 分配权限
        /// </summary>
        [HttpPost("assign")]
        public async Task<IActionResult> AssignPermissions([FromBody] AssignPermissionRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { success = false, message = "参数验证失败", errors = ModelState });
                }

                var result = await _permissionService.AssignPermissionsAsync(request);
                if (result)
                {
                    return Ok(new { success = true, message = "权限分配成功" });
                }
                return BadRequest(new { success = false, message = "权限分配失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分配权限失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取角色权限
        /// </summary>
        [HttpGet("roles/{roleId}/permissions")]
        public async Task<IActionResult> GetRolePermissions(int roleId)
        {
            try
            {
                var permissions = await _permissionService.GetRolePermissionsAsync(roleId);
                return Ok(new { success = true, data = permissions });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取角色权限失败，角色ID: {RoleId}", roleId);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        [HttpGet("users/{userId}/permissions")]
        public async Task<IActionResult> GetUserPermissions(int userId)
        {
            try
            {
                var permissions = await _permissionService.GetUserPermissionsAsync(userId);
                return Ok(new { success = true, data = permissions });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户权限失败，用户ID: {UserId}", userId);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }
    }
}